<template>
  <span
    style="position: relative"
    :class="[this.FilterIsClassic ? 'filter-item-value-numberrange-panel' : '']"
  >
    <input
      type="text"
      :class="[
        !this.FilterIsClassic ? 'filter-value' : 'filter-value-range-classic',
      ]"
      @input="startInputChange"
      :value="startValue_proxy"
      v-autowidth="{
        maxWidth: !!this.FilterIsClassic ? '40%' : '50px',
        minWidth: !!this.FilterIsClassic ? '40%' : '10px',
        comfortZone: 0,
      }"
      :tabIndex="tabIndex"
      @keydown="filterValueKeyDown"
      :placeholder="Filter.startPlaceholder"
      @change="startValueChange"
    />
    <span>-</span>
    <input
      type="text"
      :class="[
        !this.FilterIsClassic ? 'filter-value' : 'filter-value-range-classic',
      ]"
      @keydown="filterValueKeyDown"
      @input="endInputChange"
      :value="endValue_proxy"
      :placeholder="Filter.endPlaceholder"
      v-autowidth="{
        maxWidth: !!this.FilterIsClassic ? '40%' : '50px',
        minWidth: !!this.FilterIsClassic ? '40%' : '10px',
        comfortZone: 0,
      }"
      :tabIndex="tabIndex"
      placeholder=""
      @change="endValueChange"
    />
  </span>
</template>

<script>
import VueInputAutowidth from '../directive/auto-width';
import _ from 'lodash';
import { Terms } from '../config/resouce';
import readCookie from '../utils/readCookie';
import { useQuasar } from '@teld/q-components';

const Funcs = window.Funcs || {
  Notify: () => {},
  GetTerms: () => {},
  AtVarTransform: () => {},
  FasRequestTagAdd: () => {},
  Confirm: () => {},
  DateTimeToString: () => {},
  DateToString: () => {},
};

//千分位
let group = ',';
//小数点
let decimal = '.';
if (readCookie && readCookie('teld_locale')) {
  //千分位
  group = new Intl.NumberFormat(readCookie('teld_locale') || 'zh-CN')
    .format(1111)
    .replace(/1/g, '');
  //小数点
  decimal = new Intl.NumberFormat(readCookie('teld_locale') || 'zh-CN')
    .format(1.1)
    .replace(/1/g, '');
}
export default {
  directives: { autowidth: VueInputAutowidth },

  name: 'NumberRange',

  props: ['FilterValue', 'FilterIsClassic', 'tabIndex','Filter'],

  components: {},

  data() {
    return {
      startValue: (() => {
        // if (!!this.FilterIsClassic)
        // {
        //   return "";
        // }

        let _value =Array.isArray(this.FilterValue)?this.FilterValue[0]: this.FilterValue.split(' - ')[0] ?? '';
        return this.isNumber(_value) ? _value : '';
      })(),
      endValue: (() => {
        // if (!!this.FilterIsClassic)
        // {
        //   return "";
        // }

        let _value = Array.isArray(this.FilterValue)?this.FilterValue[1]: this.FilterValue.split(' - ')[1] ?? '';
        return this.isNumber(_value) ? _value : '';
      })(),
    };
  },

  computed: {
    startValue_proxy() {
      if (!this.startValue && this.startValue !== 0) return '';
      return this.numberToString(this.startValue);
    },
    endValue_proxy() {
      if (!this.endValue && this.endValue !== 0) return '';
      return this.numberToString(this.endValue);
    },
  },

  watch: {
    startValue: function (newValue, oldValue) {
      if (
        !!this.FilterIsClassic &&
        this.startValue === '' &&
        this.endValue === ''
      ) {
        this.$parent.filterValue = '';
        return;
      }
      this.$parent.filterValue = this.numberToString(this.startValue) + ' - ' + this.numberToString(this.endValue);
    },
    endValue: function (newValue, oldValue) {
      if (
        !!this.FilterIsClassic &&
        this.startValue === '' &&
        this.endValue === ''
      ) {
        this.$parent.filterValue = '';
        return;
      }
      this.$parent.filterValue = this.numberToString(this.startValue) + ' - ' + this.numberToString(this.endValue);
    },
    FilterValue: function (newValue, oldValue) {
      if (!!this.FilterIsClassic && !newValue) {
        this.startValue = '';
        this.endValue = '';
        return;
      }
      if (newValue) {
        let newValueArr = Array.isArray(this.FilterValue)?this.FilterValue: this.FilterValue.split(' - ');
        this.startValue = this.isNumber(newValueArr?.[0]*1)
          ? newValueArr?.[0]
          : '';
        this.endValue = this.isNumber(newValueArr?.[1]*1) ? newValueArr?.[1] : '';
      }
    },
  },

  setup() {
    const { dialog } = useQuasar();
    return {
      notify({ message = '', type = 'info', caption = '' }) {
        Funcs.Notify(caption, message, type);
      },
      dialog,
    };
  },

  methods: {
    filterValueKeyDown(e) {
      //8 删除 13回车 30,40 上下箭头 9:Tab
      let whiteList = [8, 13, 38, 40, 9, 37, 39, 9];

      //keycode
      let allowedCharacters = new RegExp('[0-9' + decimal + '-]$');

      // 如果输入的字符不是数字或小数位分隔符，则阻止输入
      const keyCode = e.key;
      if (whiteList.includes(e.keyCode)) {
      } else if (
        e.key == decimal &&
        e.target.value &&
        e.target.value.indexOf(decimal) == -1
      ) {
      } else if (allowedCharacters.test(keyCode)) {
      } else if (
        (e.keyCode >= 48 && e.keyCode <= 57) ||
        (e.keyCode >= 96 && e.keyCode <= 105)
      ) {
      } else if (e.ctrlKey) {
      } else {
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
    },
    startInputChange(e) {
      this.inputChange(e, 'start');
    },
    endInputChange(e) {
      this.inputChange(e, 'end');
    },
    inputChange(e, type) {
      // console.log('======inpoutchange======', e);
      var inputValue = e.target.value.replace(/。/gi, '.').replace(/，/gi, ',');
      if (!/^[0-9,.-]+$/.test(inputValue)) {
        inputValue = inputValue.replace(/[^0-9,.-]/g, '');
      }
      let precision = inputValue.split(decimal);
      if (precision[1] && precision[1].length > self.precision) {
        precision[1] = precision[1].substr(0, self.precision);
        inputValue = precision.join(decimal);
      }
      //最后一位是0继续输入bucheck，在blur统一格式化
      if (
        inputValue.indexOf(decimal) != -1 &&
        inputValue[inputValue.length - 1] == 0
      ) {
        return;
      }
      if (
        inputValue[inputValue.length - 1] == decimal &&
        inputValue.substr(0, inputValue.length - 1).indexOf(decimal) != -1
      ) {
        inputValue = inputValue.substr(0, inputValue.length - 1);
        e.target.value = inputValue;
      }
      if (inputValue.indexOf('-') == 0) {
        if (inputValue.split('-').length > 2) {
          inputValue = '-' + inputValue.replace(/-/gi, '');
        }
      } else {
        inputValue = inputValue.replace(/-/gi, '');
      }
      if (inputValue.indexOf('-') == 0 && inputValue.length == 1) {
        return;
      }
      if (!inputValue) return;
      if (
        inputValue.split(decimal)[1] &&
        Number(inputValue.split(decimal)[1]) == 0
      ) {
        return (e.target.value = inputValue);
      }
      if (inputValue.indexOf(decimal) == 0 && inputValue.length == 1) {
        return (inputValue = '');
      }
      //过滤多位
      if (
        inputValue[inputValue.length - 1] == decimal &&
        inputValue.indexOf(decimal) == inputValue.length - 1
      ) {
      } else {
        let realValue = this.stringToNumber(inputValue);
        //超出15
        if (realValue.toString().length > 15) {
          realValue = realValue.toString().substr(0, 15);
        }
        if (type == 'start') {
          this.startValue = realValue;
          if (this.endValue == '') {
            this.endValue = 0;
          }
        } else {
          this.endValue = realValue;
          if (this.startValue == '') {
            this.startValue = 0;
          }
        }
        inputValue = this.numberToString(realValue);
        e.target.value = inputValue;
      }
    },
    numberToString(
      nmb,
      local = readCookie('teld_locale') || 'zh-CN',
      useGrouping = false,
    ) {
      let decimal = '.';
      let _precision =
        nmb.toString().indexOf(decimal) != -1
          ? nmb.toString().split(decimal)[1].length
          : 0;
      let precision = this.precision;
      if (!this.precision && this.precision != 0) {
        precision = _precision;
      }
      return (function(){
        const formatted = new Intl.NumberFormat(local, {
          maximumFractionDigits: precision,
          minimumFractionDigits: precision,
          useGrouping: useGrouping,
        }).format(nmb);
        try{
          if ((Object.is && Object.is(nmb, -0)) && !/^-/.test(formatted)) {
            return '-' + formatted;
          }
          return formatted;
        }catch(e){
          if ((nmb===0 && (1/nmb)===-Infinity) && !/^-/.test(formatted)){
            return '-' + formatted;
          }
          return formatted;
        }
      })();
      return new Intl.NumberFormat(local, {
        maximumFractionDigits: precision,
        minimumFractionDigits: precision,
        useGrouping: useGrouping,
      }).format(nmb);
    },
    stringToNumber(nmbStr, local = readCookie('teld_locale') || 'zh-CN') {
      if (!nmbStr && nmbStr != '0') return '';
      //千分位
      let group = new Intl.NumberFormat(local).format(1111).replace(/1/g, '');
      //小数点
      let decimal = new Intl.NumberFormat(local).format(1.1).replace(/1/g, '');
      let reversedVal = nmbStr.replace
        ? nmbStr
            .replace(new RegExp('\\' + group, 'g'), '')
            .replace(new RegExp('\\' + decimal, 'g'), '.')
        : nmbStr;
      return Number(reversedVal);
    },
    isNumber: function (val) {
      if(val===false||val===null||typeof val ==='undefined') return false
      let locale = readCookie('teld_locale') || 'zh-CN';
      //千分位
      let group = new Intl.NumberFormat(locale).format(1111).replace(/1/g, '');
      //小数点
      let decimal = new Intl.NumberFormat(locale).format(1.1).replace(/1/g, '');
      val = val&&val.toString();
      let reversedVal = val.replace
        ? val
            .replace(new RegExp('\\' + group, 'g'), '')
            .replace(new RegExp('\\' + decimal, 'g'), '.')
        : val;
      val = Number(reversedVal);
      var RegexTest =
        /^-?(?:[0-9]+\d*(\.\d*)?|0?\.\d*[1-9]\d*|0+[1-9]\d*(\.\d*)?)$/;
      return RegexTest.test(val);
    },
    startValueChange(e) {
      let _input = e.target;
      if (_input.value !== '' && !this.isNumber(_input.value)) {
        // Funcs.Notify(
        //   Terms.Notify.warningTitle,
        //   Terms.Notify.warningText_checkTypeNumber,
        //   'warning',
        // );
        this.notify({
          caption: Terms.Notify.warningTitle,
          type: 'warning',
          message: Terms.Notify.warningText_checkTypeNumber,
        });

        _input.setSelectionRange(0, 0);
        _input.setSelectionRange(0, _input.value.length);
        _input.focus();
      } else {
        this.startValue = this.stringToNumber(_input.value);
      }
    },
    endValueChange(e) {
      let _input = e.target;
      if (_input.value !== '' && !this.isNumber(_input.value)) {
        // Funcs.Notify(
        //   Terms.Notify.warningTitle,
        //   Terms.Notify.warningText_checkTypeNumber,
        //   'warning',
        // );
        this.notify({
          caption: Terms.Notify.warningTitle,
          type: 'warning',
          message: Terms.Notify.warningText_checkTypeNumber,
        });

        _input.setSelectionRange(0, 0);
        _input.setSelectionRange(0, _input.value.length);
        _input.focus();
      } else {
        this.endValue = this.stringToNumber(_input.value);
      }
    },
  },
};
</script>

<style></style>
